package org.example.dingtalkintegrationservice.dingtalk.processInstance;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.dingtalkintegrationservice.exception.WrongFormatExceptionGroovy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author pc
 */
@Component
public class CreateProcessInstancePrepare {
    public String convert(String input){
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> maps;
        try{
            maps= objectMapper.readValue(input, new TypeReference<List<Map<String, Object>>>() {});
        }
        catch (JsonProcessingException e){
            throw new WrongFormatExceptionGroovy(input, e.getCause(),"toListMap");
        }
        for (Map<String, Object> map : maps) {
            if(!map.containsKey("value")){
                throw new WrongFormatExceptionGroovy(map.toString(),"getValue");
            }
            String value=map.get("value").toString();
            if (value.isEmpty())
            {
                map.put("value"," ");
                map.put("type","TextFieldInstance");
//                throw new WrongFormatExceptionGroovy(value,"convertValuePrepare")
            }
            else
            if (value.charAt(0)=='[') {
                try {
                    List<List<Map<String,Object>>> contents=objectMapper.readValue(value, new TypeReference<List<List<Map<String, Object>>>>() {});
                    contents.forEach(c->{
                        c.forEach(c1->{
                            c1.put("type","TextFieldInstance");
                        });
                    });
                map.put("value", contents);
                map.put("type","TableFieldInstance");
            }
            catch (JsonProcessingException e){
                throw new WrongFormatExceptionGroovy(input, e.getCause(),"toListListMap");
            }
            } else {
                map.put("type","TextFieldInstance");
            }
        }
        return JSON.toJSONString(maps);
    }
//static void main(String[] args){
//    def input="[{\"name\":\"附件\",\"value\":\"[[{\\\"name\\\":\\\"附件链接\\\",\\\"value\\\":\\\"http://110.40.229.246:8082/202412110011_2024_12_16_10_20_23.pdf\\\"}],[{\\\"name\\\":\\\"附件链接\\\",\\\"value\\\":\\\"http://110.40.229.246:8082/202412110022_2024_12_16_10_20_23.pdf\\\"}]]\"}]"
//    print(convert(input))
//}

//def exec(String input){
//    return convert(input)
//}
//sadas

}
